package com.aniu.smslisten.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LogToFile {
    private static final String TAG = "LogToFile";
    private static final String LOG_FILE_NAME = "app_log.txt";

    // 新增类变量，存储当前日期和日志文件对象
    private static String currentDate;
    private static File currentFile;

    public static void log(Context context, String tag, String message) {
        try {
            File logDir = context.getExternalFilesDir(null);
            if (logDir == null || !logDir.exists()) {
                logDir.mkdirs();
            }

            // 获取当前日期
            String newDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

            // 如果日期发生变化或文件对象为空，则更新日志文件
            if (!newDate.equals(currentDate) || currentFile == null) {
                currentDate = newDate;
                currentFile = new File(logDir, currentDate + "_" + LOG_FILE_NAME);

                if (!currentFile.exists()) {
                    currentFile.createNewFile();
                }
            }

            FileWriter writer = new FileWriter(currentFile, true);
            writer.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()))
                    .append(" [").append(tag).append("] ").append(message).append("\n");
            writer.flush();
            writer.close();
        } catch (IOException e) {
            Log.e(TAG, "Error writing to log file", e);
        }
    }

    // 新增方法：支持接收 Exception 参数
    public static void log(Context context, String tag, String message, Exception e) {
        log(context, tag, message + " - Exception: " + e.getMessage());
    }

    // 新增方法：删除5天前的日志文件
    public static void deleteOldLogs(Context context) {
        File logDir = context.getExternalFilesDir(null);
        if (logDir == null || !logDir.exists()) {
            return;
        }

        long fiveDaysAgo = System.currentTimeMillis() - (5 * 24 * 60 * 60 * 1000L); // 5天前的时间戳
        File[] files = logDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().endsWith(LOG_FILE_NAME) && file.lastModified() < fiveDaysAgo) {
                    file.delete(); // 删除5天前的日志文件
                }
            }
        }
    }
}